package au.com.betaversion.patientrecords.controller;

import java.text.SimpleDateFormat;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import au.com.betaversion.patientrecords.domain.Child;
import au.com.betaversion.patientrecords.domain.Gender;
import au.com.betaversion.patientrecords.domain.Patient;
import au.com.betaversion.patientrecords.repository.GenderRepository;
import au.com.betaversion.patientrecords.repository.PatientRepository;

@Controller
@RequestMapping("child")
public class ChildController {
	
	@Autowired
	private GenderRepository genderRepository;
	
	@Autowired
	private PatientRepository patientRepository;
	
	@ModelAttribute("gender")
	public Iterable<Gender> getGenderList() {
		return genderRepository.findAll();
	}
	
	@RequestMapping(value="add/{parent}", method = RequestMethod.GET)
	public String addChildGet(Model model, @PathVariable("parent") int parent) {
		model.addAttribute("parent", parent);
		model.addAttribute("childForm", new Child());
		return "child-add";
	}

	@RequestMapping(value="add/{parent}", method = RequestMethod.POST)
	public ModelAndView addChildPost(@ModelAttribute("childForm") Child child, @PathVariable("parent") int parent, HttpServletRequest request) {
		Patient patient = patientRepository.findOne(parent);
		if(patient != null) {
			patient.getChildren().add(child);
			patientRepository.save(patient);
		}
		return new ModelAndView(new RedirectView(request.getContextPath() + "/patient"));
	}

	@InitBinder
	public void initBinder(WebDataBinder dataBinder) {
		SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
		CustomDateEditor dateEditor = new CustomDateEditor(dateFormat, false);
		dataBinder.registerCustomEditor(java.util.Date.class, dateEditor);
	}

}